<template>
  <div class="body-login" ref="bgContainer">
    <div class="wrapper">
      <div class="front">
        <div class="title"><b>花智用户登录</b></div>
        <el-form :model="user" :rules="rules" ref="userForm">
          <!-- 修改为user.username -->
          <el-form-item prop="username">
            <el-input 
              placeholder="请输入用户名" 
              v-model="user.username"
              prefix-icon="el-icon-user"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              placeholder="请输入密码"
              v-model="user.password"
              prefix-icon="el-icon-lock"
              show-password
              @focus="showPasswordMeter = true"
            />
          </el-form-item>

          <el-form-item v-if="showCaptcha" prop="captcha">
            <el-input
              placeholder="请输入验证码"
              v-model="user.captcha"
            />
            <img :src="captchaImage" @click="refreshCaptcha" class="captcha-img"/>
          </el-form-item>

          <div class="actions">
            <el-button type="primary" @click="login" :loading="loading">
              登录
            </el-button>
            <el-button type="warning" @click="$router.push('/register')">
              注册
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
    
    <div v-if="bgLoading" class="loading-indicator">
      背景加载中...
    </div>
  </div>
</template>

<script>
import { ref, getCurrentInstance } from 'vue' // 引入getCurrentInstance
import { useRouter } from 'vue-router'
import axios from 'axios'

// 配置后端接口基础URL
const userService = axios.create({
  baseURL: '/api/userservice',
  headers: {
    'Content-Type': 'application/json' // 明确指定JSON格式
  }
})

// 响应拦截器
userService.interceptors.response.use(
  (response) => response,
  (error) => {
    const msg = error.response?.data?.msg || '请求失败，请重试'
    ElMessage({
        message: msg,
        type: 'error',
        duration: 3000, // 3秒后自动关闭
        showClose: true // 显示关闭按钮
    })
    return Promise.reject(error)
  }
)

export default {
  name: "Login",
  setup() {
    const router = useRouter()
    const { proxy } = getCurrentInstance() // 获取当前实例
    const userForm = ref(null)
    const bgContainer = ref(null)
    
    // 修改为username
    const user = ref({
      username: '',
      password: '',
      captcha: ''
    })

    const showCaptcha = ref(false)
    const captchaImage = ref('')
    const mockCaptcha = ref('1234')
    const loading = ref(false)
    const loginAttempts = ref(0)

    const refreshCaptcha = () => {
      mockCaptcha.value = Math.random().toString().slice(2, 6)
      captchaImage.value = `data:image/svg+xml;base64,${btoa(`<svg width="100" height="30"><text x="10" y="20">${mockCaptcha.value}</text></svg>`)}`
    }

    const login = async () => {
      try {
        loading.value = true
        await userForm.value.validate()
        
        const loginData = {
          username: user.value.username,
          password: user.value.password,
        }

        console.log('发送登录请求', loginData)
        // 使用await并确保路径正确
        const response = await userService.post('/api/userservice/user/login', loginData)
        
        console.log('登录响应:', response.data) // 打印响应数据

        if (response.data.success) {
          localStorage.setItem("user", JSON.stringify(response.data.data))
          localStorage.setItem("menus", JSON.stringify(response.data.data.menus))
          console.log('准备跳转到首页') // 添加日志
          await router.push("/home")
          console.log('跳转完成') // 确认跳转是否执行
      
      proxy.$message.success("登录成功") // 使用proxy
        } else {
          loginAttempts.value++
          if (loginAttempts.value >= 3) {
            showCaptcha.value = true
            refreshCaptcha()
          }
          proxy.$message.error(response.data.msg) // 使用proxy
        }
      } catch (error) {
        console.error('登录失败:', error)
        if (error.response?.status === 429) {
          showCaptcha.value = true
          refreshCaptcha()
        }
        proxy.$message.error(error.message || '登录失败') // 使用proxy
      } finally {
        loading.value = false
      }
    }

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
      ]
    }

    return {
      userForm,
      bgContainer,
      user,
      rules,
      showCaptcha,
      captchaImage,
      loading,
      loginAttempts,
      login,
      refreshCaptcha,
      mockCaptcha
    }
  },
  data() {
    return {
      bgLoaded: false,
      bgLoading: false,
      bgError: false
    }
  },
  mounted() {
    this.setupLazyLoad()
  //  this.fetchCsrfToken()
  },
  methods: {
    // 获取CSRF Token（保留原逻辑）
    // async fetchCsrfToken() {
    //   try {
    //     const response = await axios.get('/api/csrf-token')
    //     setCsrfToken(response.data.token)
    //   } catch (error) {
    //     console.error('获取CSRF令牌失败:', error)
    //   }
    // },

    // 背景图懒加载（保留原逻辑）
    setupLazyLoad() {
      if (!window.IntersectionObserver) {
        this.loadBackground()
        return
      }
      
      const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting && !this.bgLoaded) {
            this.loadBackground()
            observer.unobserve(entry.target)
          }
        })
      }, { rootMargin: '200px' })

      this.$nextTick(() => {
        if (this.$refs.bgContainer) {
          observer.observe(this.$refs.bgContainer)
        }
      })
    },

    loadBackground() {
      this.bgLoading = true;
      try {
        const imgUrl = new URL('@/assets/images/background.jpg', import.meta.url).href;
        this.$refs.bgContainer.style.backgroundImage = `url(${imgUrl})`;
        this.bgLoaded = true;
      } catch (e) {
        console.error('加载背景图失败:', e);
        this.bgError = true;
        this.$refs.bgContainer.style.backgroundColor = '#f0f2f5';
      } finally {
        this.bgLoading = false;
      }
    }
  }
}
</script>


<style scoped>
.body-login {
  background-color: #f0f2f5;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  height: 100vh;
  width: 100%;
  transition: background-image 0.5s ease;
}

.wrapper {
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.front {
  background-color: rgba(255, 255, 255, 0.7);
  width: 350px;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  margin: 20px 0;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}

.actions {
  margin: 30px 0;
  text-align: center;
}

.captcha-img {
  margin-top: 10px;
  height: 40px;
  cursor: pointer;
}

.loading-indicator {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background: rgba(0,0,0,0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
}
</style>
